<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 左侧合同类型树 -->
      <el-col :span="6" :xs="24">
        <div class="head-container">
          <el-row :gutter="10" class="mb8">
            <el-col :span="18">
              <el-input
                v-model="typeNameKey"
                placeholder="请输入类型名称"
                clearable
                size="small"
                prefix-icon="el-icon-search"
                @keyup.enter.native="filterTypeTree"
              />
            </el-col>
            <el-col :span="6">
              <el-button
                type="info"
                plain
                icon="el-icon-sort"
                size="mini"
                @click="toggleExpandAll"
              >{{ isExpandAll ? '折叠' : '展开' }}</el-button>
            </el-col>
          </el-row>
          <el-row :gutter="10" class="mb8">
            <el-col :span="18">
              <el-input
                v-model="typeCodeKey"
                placeholder="请输入类型编码"
                clearable
                size="small"
                prefix-icon="el-icon-search"
                @keyup.enter.native="filterTypeTree"
              />
            </el-col>
            <el-col :span="6">
              <el-button
                type="primary"
                plain
                icon="el-icon-search"
                size="mini"
                @click="filterTypeTree"
              >搜索</el-button>
            </el-col>
          </el-row>
        </div>
        <el-tree
          v-if="refreshTree"
          :data="typeOptions"
          :props="defaultProps"
          :expand-on-click-node="false"
          :filter-node-method="filterNode"
          :default-expand-all="isExpandAll"
          ref="tree"
          highlight-current
          @node-click="handleNodeClick"
        />
      </el-col>
      <!-- 右侧模板列表 -->
      <el-col :span="18" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
          <el-form-item label="模板名称" prop="templateName">
            <el-input
              v-model="queryParams.templateName"
              placeholder="请输入模板名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="模板状态" clearable>
              <el-option
                v-for="dict in dict.type.sys_normal_disable"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['system:contractTemplate:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="handleImportJson"
              v-hasPermi="['system:contractTemplate:import']"
            >导入JSON</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['system:contractTemplate:remove']"
            >删除</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="templateList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="模板名称" align="center" prop="templateName" :show-overflow-tooltip="true" />
          <el-table-column label="文件类型" align="center" prop="fileType" width="100">
            <template slot-scope="scope">
              <el-tag size="mini" type="success" v-if="scope.row.fileType === 'docx'">DOCX</el-tag>
              <el-tag size="mini" type="primary" v-else-if="scope.row.fileType === 'pdf'">PDF</el-tag>
              <el-tag size="mini" v-else>{{scope.row.fileType.toUpperCase()}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="文件大小" align="center" prop="fileSize" width="100">
            <template slot-scope="scope">
              {{ formatFileSize(scope.row.fileSize) }}
            </template>
          </el-table-column>
          <el-table-column label="关联类型" align="center" prop="typeNames" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <el-tag
                v-for="typeName in scope.row.typeNames"
                :key="typeName"
                size="mini"
                style="margin-right: 5px; margin-bottom: 5px;"
              >{{ typeName }}</el-tag>
              <span v-if="!scope.row.typeNames || scope.row.typeNames.length === 0">无</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" prop="status" width="100">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['system:contractTemplate:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-view"
                @click="handlePreview(scope.row)"
              >预览</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-download"
                @click="handleDownload(scope.row)"
              >下载</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:contractTemplate:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改合同模板对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="780px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="模板名称" prop="templateName">
          <el-input v-model="form.templateName" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="模板描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入模板描述" />
        </el-form-item>
        <el-form-item label="关联类型" prop="typeIds">
          <treeselect
            v-model="form.typeIds"
            :options="contractTypeOptions"
            :normalizer="normalizer"
            :show-count="true"
            multiple
            placeholder="请选择关联的合同类型"
          />
        </el-form-item>
        <el-form-item label="模板文件" prop="fileId">
          <el-upload
            class="upload-demo"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :on-preview="handleFilePreview"
            :on-remove="handleFileRemove"
            :on-success="handleFileSuccess"
            :on-error="handleFileError"
            :before-upload="beforeFileUpload"
            :file-list="fileList"
            :limit="1"
            :on-exceed="handleExceed"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传docx/pdf文件，且不超过10MB</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 预览模板对话框 -->
    <el-dialog title="模板预览" :visible.sync="previewOpen" width="80%" append-to-body>
      <div class="preview-container" v-loading="previewLoading">
        <!-- PDF预览 -->
        <iframe v-if="previewUrl && fileType === 'pdf'" :src="previewUrl" frameborder="0" class="preview-iframe"></iframe>
        
        <!-- Word文档预览 - 使用Office Online或提供下载链接 -->
        <div v-else-if="previewUrl && (fileType === 'docx' || fileType === 'doc')" class="word-preview">
          <div class="preview-header">
            <i class="el-icon-document"></i>
            <span>{{ previewFileName }}</span>
          </div>
          <div class="preview-options">
            <p>Word文档无法直接在浏览器中预览，您可以：</p>
            <el-button type="primary" @click="openInNewTab">在新窗口中打开</el-button>
            <el-button type="success" @click="handleDownload(currentPreviewTemplate)">下载文件</el-button>
          </div>
        </div>
        
        <!-- 其他类型文件 -->
        <div v-else-if="previewUrl" class="other-preview">
          <div class="preview-header">
            <i class="el-icon-document"></i>
            <span>{{ previewFileName }}</span>
          </div>
          <div class="preview-options">
            <p>此类型文件无法直接预览，您可以：</p>
            <el-button type="primary" @click="openInNewTab">在新窗口中打开</el-button>
            <el-button type="success" @click="handleDownload(currentPreviewTemplate)">下载文件</el-button>
          </div>
        </div>
        
        <!-- 无预览内容 -->
        <div v-else class="preview-placeholder">
          <i class="el-icon-document"></i>
          <p>暂无预览内容</p>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="previewOpen = false">关 闭</el-button>
        <el-button type="primary" @click="handleDownload(currentPreviewTemplate)">下 载</el-button>
      </div>
    </el-dialog>

    <!-- 导入JSON对话框 -->
    <el-dialog :title="'导入JSON数据'" :visible.sync="importOpen" width="500px" append-to-body>
      <el-form ref="importForm" :model="importForm" label-width="80px">
        <el-form-item label="JSON数据">
          <el-input
            type="textarea"
            :rows="10"
            v-model="importForm.jsonData"
            placeholder="请粘贴JSON数据"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitImportJson">确 定</el-button>
        <el-button @click="cancelImport">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listContractType } from "@/api/system/contractType";
import { listContractTemplate, getContractTemplate, delContractTemplate, addContractTemplate, updateContractTemplate,
         downloadTemplate, previewTemplate, batchImportContractTemplate } from "@/api/system/contractTemplate";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getToken } from "@/utils/auth";

export default {
  name: "ContractTemplate",
  dicts: ['sys_normal_disable'],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 合同模板表格数据
      templateList: [],
      // 合同类型树选项
      typeOptions: [],
      // 合同类型下拉选项
      contractTypeOptions: [],
      // 类型ID到名称的映射
      typeIdToName: {},
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示预览弹出层
      previewOpen: false,
      // 预览加载状态
      previewLoading: false,
      // 预览URL
      previewUrl: "",
      // 当前预览的模板
      currentPreviewTemplate: null,
      // 预览文件名
      previewFileName: "",
      // 预览文件类型
      fileType: "",
      // 类型名称关键字
      typeNameKey: "",
      // 类型编码关键字
      typeCodeKey: "",
      // 当前选中的类型
      currentSelectedType: null,
      // 是否展开，默认不展开
      isExpandAll: false,
      // 重新渲染树状态
      refreshTree: true,
      // 上传地址
      uploadUrl: process.env.VUE_APP_BASE_API + '/system/contractTemplate/upload',
      // 上传头部信息
      uploadHeaders: {
        Authorization: 'Bearer ' + getToken()
      },
      // 上传文件列表
      fileList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        templateName: null,
        templateCode: null,
        status: null,
        contractTypeId: null
      },
      // 表单参数
      form: {
        templateId: undefined,
        templateName: undefined,
        description: undefined,
        typeIds: [],
        fileId: undefined,
        fileType: undefined,
        fileSize: undefined,
        status: "0",
        remark: undefined
      },
      // 表单校验
      rules: {
        templateName: [
          { required: true, message: "模板名称不能为空", trigger: "blur" }
        ],
        typeIds: [
          { required: true, message: "请选择关联的合同类型", trigger: "change" }
        ],
        fileId: [
          { required: true, message: "请上传模板文件", trigger: "change" }
        ]
      },
      // 树形配置
      defaultProps: {
        children: "children",
        label: "typeName"
      },
      // 导入JSON表单参数
      importOpen: false,
      importForm: {
        jsonData: ''
      },
    };
  },
  watch: {
    // 根据名称筛选合同类型树
    typeNameKey(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
    this.getTreeList();
    this.getTreeselect();
  },
  methods: {
    /** 查询合同类型树结构 */
    getTreeList() {
      listContractType().then(response => {
        this.typeOptions = response.data;
      });
    },
    /** 查询合同模板列表 */
    getList() {
      this.loading = true;
      listContractTemplate(this.queryParams).then(response => {
        // 处理类型名称显示
        this.templateList = response.rows.map(item => {
          if (item.typeIds) {
            item.typeNames = item.typeIds
              .map(typeId => this.typeIdToName[typeId])
              .filter(name => name);
          } else {
            item.typeNames = [];
          }
          return item;
        });
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 转换合同类型数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.typeId,
        label: node.typeName,
        children: node.children
      };
    },
    /** 查询合同类型下拉树结构 */
    getTreeselect() {
      listContractType().then(response => {
        this.contractTypeOptions = response.data;
        // 构建类型ID到名称的映射
        this.buildTypeIdNameMap(response.data);
      });
    },
    /** 构建类型ID到名称的映射 */
    buildTypeIdNameMap(types) {
      types.forEach(type => {
        this.typeIdToName[type.typeId] = type.typeName;
        if (type.children && type.children.length > 0) {
          this.buildTypeIdNameMap(type.children);
        }
      });
    },
    /** 筛选节点 */
    filterNode(value, data) {
      if (!value) return true;
      // 如果输入的值同时包含类型名称和类型编码，返回true
      return data.typeName.toLowerCase().indexOf(value.toLowerCase()) !== -1 ||
             (data.typeCode && data.typeCode.toLowerCase().indexOf(value.toLowerCase()) !== -1);
    },
    /** 节点单击事件 */
    handleNodeClick(data) {
      this.currentSelectedType = data;
      this.queryParams.contractTypeId = data.typeId;
      this.getList();
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.fileList = [];
      this.form = {
        templateId: undefined,
        templateName: undefined,
        description: undefined,
        typeIds: [],
        fileId: undefined,
        fileType: undefined,
        fileSize: undefined,
        status: "0",
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.contractTypeId = null;
      this.handleQuery();
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.templateId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      // 如果有当前选中的类型，则自动添加到表单的typeIds中
      if (this.currentSelectedType && this.currentSelectedType.typeId) {
        this.form.typeIds = [this.currentSelectedType.typeId];
      }
      this.open = true;
      this.title = "添加合同模板";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const templateId = row.templateId || this.ids[0];
      getContractTemplate(templateId).then(response => {
        this.form = response.data;
        // 如果已有文件，添加到文件列表
        if (this.form.fileName) {
          this.fileList = [{
            name: this.form.fileName,
            url: this.form.fileUrl
          }];
        }
        this.open = true;
        this.title = "修改合同模板";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 如果是新增且没有上传文件，提示错误
          if (!this.form.templateId && !this.form.fileId) {
            this.$message.error("请上传模板文件");
            return;
          }
          
          // 如果是新增且已选中类型，则将类型ID添加到类型ID列表中
          if (!this.form.templateId && this.currentSelectedType && this.currentSelectedType.typeId) {
            // 如果类型ID列表不存在，则创建一个新的列表
            if (!this.form.typeIds) {
              this.form.typeIds = [];
            }
            // 如果类型ID列表中不包含当前选中的类型ID，则添加到列表中
            if (!this.form.typeIds.includes(this.currentSelectedType.typeId)) {
              this.form.typeIds.push(this.currentSelectedType.typeId);
            }
          }
          
          if (this.form.templateId) {
            updateContractTemplate(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addContractTemplate(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const templateIds = row.templateId || this.ids;
      this.$modal.confirm('是否确认删除合同模板编号为"' + templateIds + '"的数据项？').then(function() {
        return delContractTemplate(templateIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 预览按钮操作 */
    handlePreview(row) {
      this.previewLoading = true;
      this.previewOpen = true;
      this.currentPreviewTemplate = row;
      previewTemplate(row.templateId).then(response => {
        if (response.code === 200 && response.data) {
          this.previewUrl = response.data.url;
          this.previewFileName = response.data.fileName;
          this.fileType = response.data.fileType;
        } else {
          this.previewUrl = '';
          this.previewFileName = '';
          this.fileType = '';
        }
        this.previewLoading = false;
      }).catch(() => {
        this.previewUrl = '';
        this.previewFileName = '';
        this.fileType = '';
        this.previewLoading = false;
      });
    },
    /** 下载按钮操作 */
    handleDownload(row) {
      downloadTemplate(row.templateId).then(response => {
        const blob = new Blob([response]);
        const fileName = row.templateName + '.' + row.fileType;
        if ('download' in document.createElement('a')) {
          const elink = document.createElement('a');
          elink.download = fileName;
          elink.style.display = 'none';
          elink.href = URL.createObjectURL(blob);
          document.body.appendChild(elink);
          elink.click();
          URL.revokeObjectURL(elink.href);
          document.body.removeChild(elink);
        } else {
          navigator.msSaveBlob(blob, fileName);
        }
      }).catch(() => {});
    },
    /** 文件上传前的处理 */
    beforeFileUpload(file) {
      const isDocOrPdf = file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' || 
                        file.type === 'application/pdf';
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isDocOrPdf) {
        this.$message.error('上传文件只能是 docx/pdf 格式!');
        return false;
      }
      if (!isLt10M) {
        this.$message.error('上传文件大小不能超过 10MB!');
        return false;
      }
      return true;
    },
    /** 文件上传成功的处理 */
    handleFileSuccess(response, file, fileList) {
      if (response.code === 200) {
        this.form.fileId = response.data.fileId;
        this.form.fileName = response.data.fileName;
        this.form.fileUrl = response.data.fileUrl;
        this.form.fileType = response.data.fileType;
        this.form.fileSize = response.data.fileSize;
        // 如果没有设置模板名称，使用文件名作为模板名称
        if (!this.form.templateName) {
          this.form.templateName = file.name.split('.')[0];
        }
        this.$message.success('文件上传成功');
      } else {
        this.$message.error(response.msg || '文件上传失败');
        this.fileList = [];
      }
    },
    /** 文件上传失败的处理 */
    handleFileError(err) {
      this.$message.error('文件上传失败');
      console.error(err);
      this.fileList = [];
    },
    /** 文件列表移除文件时的钩子 */
    handleFileRemove(file, fileList) {
      this.fileList = fileList;
      this.form.fileId = undefined;
      this.form.fileName = undefined;
      this.form.fileUrl = undefined;
      this.form.fileType = undefined;
      this.form.fileSize = undefined;
    },
    /** 点击已上传的文件链接时的钩子 */
    handleFilePreview(file) {
      // 可以在这里处理文件预览逻辑
    },
    /** 文件超出个数限制时的钩子 */
    handleExceed() {
      this.$message.warning('最多只能上传1个文件');
    },
    /** 格式化文件大小 */
    formatFileSize(size) {
      if (!size) return '0 KB';
      
      const units = ['B', 'KB', 'MB', 'GB'];
      let index = 0;
      let fileSize = size;
      
      while (fileSize >= 1024 && index < units.length - 1) {
        fileSize /= 1024;
        index++;
      }
      
      return fileSize.toFixed(2) + ' ' + units[index];
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTree = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTree = true;
      });
    },
    openInNewTab() {
      const url = this.previewUrl;
      const a = document.createElement('a');
      a.href = url;
      a.target = '_blank';
      a.click();
    },
    filterTypeTree() {
      const filterValue = this.typeNameKey || this.typeCodeKey;
      this.$refs.tree.filter(filterValue);
    },
    /** 导入JSON按钮操作 */
    handleImportJson() {
      this.importOpen = true;
      this.importForm.jsonData = '';
    },
    /** 取消导入按钮操作 */
    cancelImport() {
      this.importOpen = false;
      this.resetForm("importForm");
    },
    /** 提交导入JSON数据 */
    submitImportJson() {
      this.$refs["importForm"].validate(valid => {
        if (valid) {
          try {
            // 解析JSON数据
            const jsonData = JSON.parse(this.importForm.jsonData);
            // 检查是否为数组
            if (!Array.isArray(jsonData)) {
              this.$message.error('JSON数据格式不正确，应为数组格式');
              return;
            }
            
            // 处理导入的数据
            this.processImportedData(jsonData);
            this.importOpen = false;
          } catch (error) {
            this.$message.error('JSON数据解析失败: ' + error.message);
          }
        }
      });
    },
    /** 处理导入的JSON数据 */
    processImportedData(jsonData) {
      const importPromises = [];
      const successList = [];
      const failList = [];
      
      // 显示导入进度
      const loadingInstance = this.$loading({
        lock: true,
        text: '正在导入数据，请稍候...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      
      // 准备批量导入的数据
      const templateList = [];
      
      // 遍历JSON数据并创建合同模板
      jsonData.forEach(item => {
        // 查找对应的合同类型ID
        const typeId = this.findTypeIdByCategory(item.main_category, item.sub_category);
        
        if (!typeId) {
          failList.push({
            name: item.title,
            message: `未找到匹配的合同类型: ${item.main_category} - ${item.sub_category}`
          });
          return;
        }
        
        // 构建合同模板对象
        const template = {
          templateName: item.title,
          fileUrl: item.oss_path,
          typeIds: [typeId], // 使用查找到的类型ID
          status: "0" // 默认状态为正常
        };
        
        templateList.push(template);
      });
      
      // 如果没有有效的模板数据，直接返回
      if (templateList.length === 0) {
        loadingInstance.close();
        this.$notify({
          title: '导入失败',
          dangerouslyUseHTMLString: true,
          message: `
            <div>没有有效的模板数据可导入</div>
            ${failList.length > 0 ? '<div>失败列表:</div>' + 
              failList.map(item => `<div>${item.name}: ${item.message}</div>`).join('') : ''}
          `,
          type: 'error',
          duration: 5000
        });
        return;
      }
      
      // 调用批量导入接口
      batchImportContractTemplate(templateList)
        .then(response => {
          loadingInstance.close();
          
          // 显示导入结果
          this.$notify({
            title: '导入完成',
            dangerouslyUseHTMLString: true,
            message: `
              <div>成功导入: ${response.msg}</div>
              ${failList.length > 0 ? '<div>失败列表:</div>' + 
                failList.map(item => `<div>${item.name}: ${item.message}</div>`).join('') : ''}
            `,
            type: 'success',
            duration: 5000
          });
          
          // 刷新列表
          this.getList();
        })
        .catch(error => {
          loadingInstance.close();
          this.$message.error('导入过程中发生错误: ' + error.message);
        });
    },
    /** 根据主分类和子分类查找合同类型ID */
    findTypeIdByCategory(mainCategory, subCategory) {
      // 如果合同类型选项还未加载，先加载
      if (this.contractTypeOptions.length === 0) {
        return null;
      }
      
      // 查找主分类
      const mainType = this.contractTypeOptions.find(
        type => type.typeName === mainCategory
      );
      
      if (!mainType || !mainType.children) {
        return null;
      }
      
      // 查找子分类
      const subType = mainType.children.find(
        type => type.typeName === subCategory
      );
      
      return subType ? subType.typeId : null;
    },
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.head-container {
  margin-bottom: 10px;
}

.mb8 {
  margin-bottom: 8px;
}

.preview-container {
  width: 100%;
  height: 70vh;
  overflow: hidden;
  position: relative;
}

.preview-iframe {
  width: 100%;
  height: 100%;
  border: none;
}

.preview-placeholder, .word-preview, .other-preview {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.preview-placeholder i, .word-preview i, .other-preview i {
  font-size: 48px;
  color: #909399;
  margin-bottom: 20px;
}

.preview-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.preview-header i {
  font-size: 24px;
  margin-right: 10px;
  margin-bottom: 0;
}

.preview-options {
  text-align: center;
  margin-top: 20px;
}

.preview-options p {
  margin-bottom: 15px;
  color: #606266;
}

.preview-options .el-button {
  margin: 0 10px;
}
</style>
